import { Provide } from "@midwayjs/core";
import { BaseService, CoolCommException, CoolTransaction } from "@cool-midway/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository, QueryRunner } from "typeorm";
import { OrderVerifyEntity } from "../../order/entity/verify";
import { OrderInfoEntity } from "../../order/entity/info";
import { OrderItemEntity } from "../../order/entity/item";

/**
 * 核销服务
 */
@Provide()
export class OrderVerifyService extends BaseService {
    @InjectEntityModel(OrderVerifyEntity)
    orderVerifyEntity: Repository<OrderVerifyEntity>;

    @InjectEntityModel(OrderInfoEntity)
    orderInfoEntity: Repository<OrderInfoEntity>;

    @InjectEntityModel(OrderItemEntity)
    orderItemEntity: Repository<OrderItemEntity>;

    /**
     * 生成核销码：为订单或子项生成一条未核销记录
     */
    @CoolTransaction()
    async generateCode(
        params: { orderId?: number; itemId?: number },
        queryRunner?: QueryRunner
    ) {
        const { orderId, itemId } = params || {};
        if (!orderId && !itemId) throw new CoolCommException('缺少订单或子项标识');

        if (itemId) {
            const item = await queryRunner.manager.findOne(OrderItemEntity, { where: { id: itemId } });
            if (!item) throw new CoolCommException('订单子项不存在');
        }
        if (orderId) {
            const order = await queryRunner.manager.findOne(OrderInfoEntity, { where: { id: orderId } });
            if (!order) throw new CoolCommException('订单不存在');
        }

        // 生成唯一码（简单实现）
        let code = '';
        for (let i = 0; i < 5; i++) {
            const candidate = Math.random().toString(36).slice(2, 10);
            const exists = await queryRunner.manager.findOne(OrderVerifyEntity, { where: { code: candidate } });
            if (!exists) { code = candidate; break; }
        }
        if (!code) throw new CoolCommException('核销码生成失败，请重试');

        const insertRes = await queryRunner.manager.insert(OrderVerifyEntity, {
            orderId: orderId || null,
            itemId: itemId || null,
            code,
            status: 0,
        });
        return { code, id: insertRes.identifiers?.[0]?.id };
    }

    /**
     * 核销：根据核销码将状态置为已核销
     */
    @CoolTransaction()
    async consume(params: { code: string }, queryRunner?: QueryRunner) {
        const { code } = params || {};
        if (!code) throw new CoolCommException('缺少核销码');

        const verify = await queryRunner.manager.findOne(OrderVerifyEntity, { where: { code, status: 0 } });
        if (!verify) throw new CoolCommException('核销码不存在或已使用');

        await queryRunner.manager.update(
            OrderVerifyEntity,
            { id: verify.id },
            { status: 1, verifyTime: new Date().toISOString() }
        );
        return true;
    }
}


